package com.xuetang9.BBS.commons.formater;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.springframework.format.Formatter;


/**
 * 日期格式转化
 * @author Administrator
 *
 */
public class DateFormater implements Formatter<Date> {

	private String[] patterns;
	
	private String selectedpattern;

	public DateFormater(String[] patterns) {
		this.patterns = patterns;
	}

	@Override
	public String print(Date date, Locale locale) {
			
		if(date==null){
			return "";
		}
		SimpleDateFormat dateformat = new SimpleDateFormat(selectedpattern);
		return dateformat.format(date);
	}

	@Override
	public Date parse(String value, Locale locale) throws ParseException {
		if (value == null || value.length() == 0) {
			return null;
		}

		Date date = null;

		for (String pattern : patterns) {
			SimpleDateFormat dateformat = new SimpleDateFormat(pattern);
			try {
				date = dateformat.parse(value);
				selectedpattern=pattern;
				break;
			} catch (ParseException e) {
			}
		}
		if (date == null) {
			String message = "日期格式部正确：日期必须是以下格式=>";
			for (String string : patterns) {
				message += string;
			}
			throw new RuntimeException(message);
		}
		return date;

	}

}
